package blog.utils;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

public class QiniuUtils {

    public static final String url = "http://r5umfy6bq.hb-bkt.clouddn.com/";

    public static boolean upload(MultipartFile file,String fileName) {

        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.huabei());

        UploadManager uploadManager = new UploadManager(cfg);

        //...生成上传凭证，然后准备上传
        String accessKey = "Gbw80WHvU1tI9G6ObNUoejof-nSa1YSW2KWVbGau";
        String secretKey = "v3cR9TVUlzWp_wBQ1ZXh2f8mqQqbUjIiCMFieT3G";
        String bucket = "blog-markdown-images";

        // 默认不指定key的情况下，以文件内容的hash值作为文件名
        try {
            byte[] uploadBytes = file.getBytes();
            Auth auth = Auth.create(accessKey, secretKey);
            String upToken = auth.uploadToken(bucket);
            Response response = uploadManager.put(uploadBytes, fileName, upToken);
            //解析上传成功的结果
            DefaultPutRet defaultPutRet = JSONUtil.toBean(response.bodyString(), DefaultPutRet.class);
            return true;
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }

        return false;

    }
}
